package com.hyst.utils;

import com.hyst.domain.FreeAudition;
import io.swagger.models.auth.In;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
import java.io.FileOutputStream;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.List;


/***
 * @Author: jiyang
 * @Date: 2018-10-31 12:49
 */
public class POIUtil {

    /**
     * 生成免费试听记录文档
     */
    public static XWPFDocument genFreeDocument(FreeAudition freeAudition) throws Exception {
        XWPFDocument document = new XWPFDocument();
        XWPFTable table = document.createTable(20, 2);

        table.getCTTbl().addNewTblGrid().addNewGridCol().setW(BigInteger.valueOf(2000));
        table.getCTTbl().getTblGrid().addNewGridCol().setW(BigInteger.valueOf(6000));
        setTableWidth(table, "8000");

        //第1行
        XWPFTableRow row0 = table.getRow(0);
        XWPFTableCell cell = row0.getCell(0);
        createXWPFParagraph(cell, "宋体", 12, "Macy English试听课预约表", true, ParagraphAlignment.CENTER);
        row0.getCell(1).setText("");

        //第2行
        XWPFTableRow row2 = table.getRow(1);
        XWPFTableCell cell2 = row2.getCell(0);
        createXWPFParagraph(cell2, "宋体", 12, "个人简明信息 Personal Information", false, ParagraphAlignment.CENTER);
        row2.getCell(1).setText("");

        List<String> cellStr = Arrays.asList("英文 name", "性别 gender", "年龄 age", "Zoom ID", "QQ号", "邮箱 Email",
                "Trial class time：您能试听的宽泛时间(几点到几点之间) ", "Regular class Time: 您正式上课的大概时间",
                "English Level Description 请简单描述您目前的英语水平", "Which aspects do you wants to improve by our class?\n您想通过美思英语课程着重加强哪些方面的学习？ ",
                "Which kinds of teachers do you prefer?\n您对老师有什么要求？",
                "Would you like small homework after each class?\n(Yes/No)您喜欢老师给孩子留简单的作业吗？(是／否) ");

        StringBuilder abilioty=new StringBuilder("");
        if(StringUtils.isNotBlank(freeAudition.getEnglishAbility())){
            String[] split = freeAudition.getEnglishAbility().split(",");
            for(String s:split){
                if("听".equals(s)){
                    abilioty.append("Listening ");
                }else if("说".equals(s)){
                    abilioty.append("Speaking ");
                }else if("读".equals(s)){
                    abilioty.append("Reading ");
                }else if("写".equals(s)){
                    abilioty.append("Writing ");
                }
            }
        }

        StringBuilder level= new StringBuilder("");
        if(StringUtils.isNotBlank(freeAudition.getEnglishLevel())){
            if("基础".equals(freeAudition.getEnglishLevel())){
                level.append("Beginner");
            }else if("初级".equals(freeAudition.getEnglishLevel())){
                level.append("Elementary");
            }else if("中级".equals(freeAudition.getEnglishLevel())){
                level.append("Pre-Intermediate");
            }
        }

        StringBuilder sex = new StringBuilder("");
        if(StringUtils.isNotBlank(freeAudition.getSex())){
            if("男".equals(freeAudition.getSex())){
                sex.append("male");
            }else {
                sex.append("female");
            }
        }

        StringBuilder homelike = new StringBuilder("");
        if(StringUtils.isNotBlank(freeAudition.getHomeworkLike())){
            if("是".equals(freeAudition.getHomeworkLike())){
                homelike.append("yes");
            }else {
                homelike.append("no");
            }
        }

//        String auditionTime="";
//        if(StringUtils.isNotBlank(freeAudition.getAuditionTime()    )){
//
//        }
        List<String> answer = Arrays.asList(defaultValue(freeAudition.getEnName(),""),
                defaultValue(sex.toString(),""),
                defaultValue(freeAudition.getAge(),""),
                defaultValue(freeAudition.getZoomId(),""),
                defaultValue(freeAudition.getQq(),""),
                defaultValue(freeAudition.getEmail(),""),
                defaultValue(freeAudition.getAuditionTime(),""),
                defaultValue(freeAudition.getFormalTime(),""),
                defaultValue(level.toString(),""),
                defaultValue(abilioty.toString(),""),
                "Please speak speed slow down a bit and make the class lively and interesting. Thank you!",defaultValue(homelike.toString(),""));

        int rowIndex = 2;
        for (int i = 0; i < cellStr.size(); i++) {
            XWPFTableRow row = table.getRow(rowIndex++);
            XWPFTableCell cell3 = row.getCell(0);
            createXWPFParagraph(cell3, "宋体", 12, cellStr.get(i), false, ParagraphAlignment.LEFT);
            if(rowIndex<=8){
                XWPFTableCell cell4 = row.getCell(1);
                createXWPFParagraph(cell4, "宋体", 12, answer.get(i), false, ParagraphAlignment.LEFT);
            }else {
                row.getCell(1).setText("");
            }

            if (i >= 6) {
                XWPFTableRow row6 = table.getRow(rowIndex++);
                XWPFTableCell cell6 = row6.getCell(0);
                createXWPFParagraph(cell6, "宋体", 12, answer.get(i), false, ParagraphAlignment.LEFT);
                row6.getCell(1).setText("");
            }
        }

        List<Integer> index = Arrays.asList(0, 1, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19);
        for (int i : index) {
            mergeCellsHorizontal(table, i, 0, 1);
        }

        XWPFParagraph xwpfParagraph = document.createParagraph();
        XWPFRun run = xwpfParagraph.createRun();
        run.setText("感谢您对美思英语的信任、理解和支持！");
        run.addBreak();
        run.setText("Thanks");
        return document;
    }

    public static XWPFParagraph createXWPFParagraph(XWPFTableCell cell, String wordStyle, Integer fontSize, String text,
                                                    boolean bold, ParagraphAlignment paragraphAlignment) {
        XWPFParagraph p = cell.addParagraph();
        p.setAlignment(paragraphAlignment);//居中

        String[] s = text.split("[\n\r]");//按回车符分割字符
        if (s.length == 1) {
            XWPFRun r = p.createRun();
            r.setFontFamily(wordStyle);
            r.setFontSize(fontSize);
            r.setText(text);//写入文本
            r.setBold(bold);
        } else {
            cell.setText(s[0]);
            for (int i = 1; i < s.length; i++) {
                XWPFRun r = p.createRun();
                r.setFontFamily(wordStyle);
                r.setFontSize(fontSize);
                r.setText(s[i]);//写入文本
                r.setBold(bold);
            }
        }

        return p;
    }

    public static void createRow(XWPFTableRow row) {
        row.setHeight(500);
        row.getCell(0).setText("");
        row.getCell(1).setText("");
    }

    /**
     *
     * @Description: 跨列合并
     */
    public static void mergeCellsHorizontal(XWPFTable table, int row, int fromCell, int toCell) {
        for (int cellIndex = fromCell; cellIndex <= toCell; cellIndex++) {
            XWPFTableCell cell = table.getRow(row).getCell(cellIndex);
            if (cellIndex == fromCell) {
                // The first merged cell is set with RESTART merge value
                cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
            } else {
                // Cells which join (merge) the first one, are set with CONTINUE
                cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);
            }
        }
    }

    /**
     * @Description: 跨行合并
     */
    public static void mergeCellsVertically(XWPFTable table, int col, int fromRow, int toRow) {
        for (int rowIndex = fromRow; rowIndex <= toRow; rowIndex++) {
            XWPFTableCell cell = table.getRow(rowIndex).getCell(col);
            if (rowIndex == fromRow) {
                // The first merged cell is set with RESTART merge value
                cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);
            } else {
                // Cells which join (merge) the first one, are set with CONTINUE
                cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);
            }
        }
    }

    public static void setTableWidth(XWPFTable table, String width) {
        CTTbl ttbl = table.getCTTbl();
        CTTblPr tblPr = ttbl.getTblPr() == null ? ttbl.addNewTblPr() : ttbl.getTblPr();
        CTTblWidth tblWidth = tblPr.isSetTblW() ? tblPr.getTblW() : tblPr.addNewTblW();
        CTJc cTJc = tblPr.addNewJc();
        cTJc.setVal(STJc.Enum.forString("center"));
        tblWidth.setW(new BigInteger(width));
        tblWidth.setType(STTblWidth.DXA);
    }


    public static String defaultValue(String value ,String def){
        if(StringUtils.isBlank(value)){
            return def;
        }
        return value;
    }


    public static String defaultValue(Integer value , String def){
        if(null==value){
            return def;
        }
        return value.toString();
    }

    public void saveDocument(XWPFDocument document, String savePath)
            throws Exception {
        FileOutputStream fos = new FileOutputStream(savePath);
        document.write(fos);
        fos.close();
    }

    public static void main(String[] args) throws Exception{
        FreeAudition freeAudition = new FreeAudition();
        freeAudition.setAuditionTime("试听时间");
        freeAudition.setEnName("luz");
        freeAudition.setAge(20);
        freeAudition.setEmail("11@qq.com");
        freeAudition.setEnglishAbility("听");
        freeAudition.setEnglishLevel("中级");
        freeAudition.setHomeworkLike("YES");
        freeAudition.setSex("男");
        freeAudition.setQq(Integer.valueOf(20686767));
        freeAudition.setZoomId("232323232323232332");

    }
}
